package com.huanzhidadi.single.collection;

import com.alibaba.fastjson2.JSON;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

public class ListTest {
    public static void main(String[] args) {
        ThreadLocalRandom random = ThreadLocalRandom.current();
        List<Integer> l1 = new ArrayList();
        // 生成初始化数据
        for (int i=0; i<10; i++) {
            l1.add(random.nextInt(10));
        }
        System.out.println("初始化列表：" + JSON.toJSONString(l1));

        Integer[] array = l1.toArray(new Integer[0]);
        System.out.println("列表转数组：" + JSON.toJSONString(array));


        System.out.println("使用forEach循环输出：");
        l1.forEach(System.out::print);
        System.out.println("");

        List<Integer> integerList = l1.stream().limit(5).sorted(((o1, o2) -> o1 > o2 ? 1 : -1)).collect(Collectors.toList());
        System.out.println("lambda先取前五再升序：" + JSON.toJSONString(integerList));

        l1.sort(((o1, o2) -> o1<o2 ? 1 : -1));
        System.out.println("降序：" + JSON.toJSONString(l1));

        System.out.println("是否包含所有元素：" + l1.containsAll(integerList));

        // lastIndexOf从末尾开始查找
        System.out.println("元素第一次出现的位置：" + l1.indexOf(7));
        /*l1.retainAll(integerList);
        System.out.println("交集：" + JSON.toJSONString(l1));*/

        ListIterator<Integer> integerListIterator = l1.listIterator(5);
        System.out.println("integerListIterator.previous()：" + integerListIterator.previous());

        Integer[] aim = {1,2,3,4,5,6,7,8,9};
        //int[] aim2 = {1,2,3,4,5,6,7,8,9};//报错；
        List<Integer> ans = Arrays.asList(aim);
        // 从第0位开始取2位
        System.out.println(ans.subList(0,2).toString());
        System.out.println(ans.subList(2,9).toString());
    }
}
